<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="添加商品信息" type="info" center :closable="false" show-icon></el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" :active="activeIndex-0" align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs标签 切换 name里面的值是字符串  需要减0 转数字-->
      <!-- 外面包裹el-form 里面就不需要每个都写 -->
      <el-form
        :model="AddRuleForm"
        :rules="addRules"
        ref="addRuleForm"
        label-position="top"
        label-width="100px"
      >
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          :before-leave="beforeLeave"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="AddRuleForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="AddRuleForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="AddRuleForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="AddRuleForm.goods_number" type="number"></el-input>
            </el-form-item>
            <!-- 级联选择 -->
            <el-form-item label="商品分类">
              <!-- v-model的值根据后台定义的 -->
              <el-cascader
                v-model="cascaderOpt"
                :options="goodsCateList"
                :props="propsObj"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyGoodsParams"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals" size="small">
                <el-checkbox :label="item1" border v-for="(item1,i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyGoodsParams" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :headers="headerObj"
              :on-success="uploadImgSuccess"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
             <quill-editor v-model="AddRuleForm.goods_introduce">
             </quill-editor>
             <el-button type="primary" style="margin-top:15px" @click="addGoods"> 添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog
      title="图片预览"
      :visible.sync="imgPreviewDialogVisible"
      width="60%">
      <img :src="imgPreviewUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cascaderOpt:[1,3,6], // 与页面绑定的数据
      activeIndex: 0,
      AddRuleForm: {
        goods_name: 'test',
        goods_price: 1,
        goods_weight: 1,
        goods_number: 1,
        goods_cat: '',  // 提交给后代的数据
        pics:[],
        goods_introduce:'',
        attrs:[]
      },
      addRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ]
      },
      goodsCateList: [],
      propsObj: {
        expandTrigger: 'hover',
        label: 'cat_name', // 渲染的名称
        value: 'cat_id' // 选中的类型值
      },
      manyGoodsParams: [],
      onlyGoodsParams:[],
      // upload请求不是axios请求，所以axios请求拦截的token值不能获取到 需要手动添加token值到请求头
      headerObj:{
        Authorization:sessionStorage.getItem('token')
      },
      
      // 图片预览弹框
      imgPreviewDialogVisible:false,
      // 图片预览路径
      imgPreviewUrl:''
    }
  },

  methods: {
    // 获取分类数据
    async getGoodsCate() {
      // 获取分类数据
      const { data: res } = await this.$http.get('categories')
      // console.log(res)
      if (res.meta.status == 200) {
        this.goodsCateList = res.data
      }
      // console.log(this.goodsCateList)
    },
    handleChange() {
      // console.log(this.cascaderOpt)
      // 限制只能选中三级分类  判断选中的数组长度
      if (this.cascaderOpt.length !== 3) {
        return (this.cascaderOpt = [])
      }
    },
    // 当切换tabs标签菜单是触发  newVal 切换对应的name值  oldVal切换前对应的name值
    beforeLeave(newVal, oldVal) {
      // console.log(newVal)
      // console.log(oldVal)
      if (oldVal == 0 && this.cascaderOpt.length !== 3) {
        this.$message.error('请选择商品分类')
        return false // 阻止向下执行
      }
    },
    // tab 被选中时触发
    async tabClick() {
      console.log(this.activeIndex)
      console.log(this.cascaderOpt)
      if (this.activeIndex == 1) {
        // 根据
        console.log(this.catId)
        const { data: res } = await this.$http.get(
          `categories/${this.catId}/attributes`,
          {
            params: {
              sel: 'many'
            }
          }
        )
        console.log(res.data)
        if (res.meta.status == 200) {
          res.data.forEach(item => {
            // "".split(' ') 得到是的[""] 会把商品参数没有可选项的参数 复选框也会出现 解决这个问题要进行判断
            item.attr_vals =
              item.attr_vals.trim().length == 0 ? [] : item.attr_vals.split(' ') // 字符串换数组 方便循环拿数据
          })
          this.manyGoodsParams = res.data
        }
        // console.log(this.manyGoodsParams)
      } else if(this.activeIndex == 2) {
        const { data: res } = await this.$http.get(
          `categories/${this.catId}/attributes`,
          {
            params: {
              sel: 'only'
            }
          }
        )
        if (res.meta.status == 200) {
          this.onlyGoodsParams = res.data
          console.log(this.onlyGoodsParams)
        }
      }
    },
    // 图片预览
    handlePreview(file) {
      // console.log(file.response.data.url)
      this.imgPreviewUrl = file.response.data.url
      this.imgPreviewDialogVisible = true
    },
    // 图片移除
    handleRemove(file) {
      // console.log(file.response.data.tmp_path)
      // console.log(this.AddRuleForm.pics)
      var index = this.AddRuleForm.pics.findIndex(item => {
        return file.response.data.tmp_path == item.pic
      })
      console.log(index)
      this.AddRuleForm.pics.splice(index,1)
      console.log(this.AddRuleForm)

    },
    // 图片上传成功
    uploadImgSuccess(res) {
      // console.log(res)
      if(res.meta.status == 200) {
        this.AddRuleForm.pics.push({"pic":res.data.tmp_path})  // pics是数组用push
      }
      console.log(this.AddRuleForm)
    },
    // 添加商品
    addGoods() {
      // 发送请求前进行预校验
      this.$refs.addRuleForm.validate(async flag => {
        if(!flag) return this.$message.error('请填写必要的表单项')
          // cascaderOpt是个数组 要转换为以逗号隔开的字符串
        this.AddRuleForm.goods_cat = this.cascaderOpt.join(',')  // 有两套数据
        // console.log(this.AddRuleForm)
        // 处理动态参数  添加到AddRuleForm.attrs中
        this.manyGoodsParams.forEach(item => {
          // console.log(item)
          this.AddRuleForm.attrs.push({
            attr_id:item.attr_id,
            attr_value:item.attr_vals.join(',')
          })
        })
        // 处理静态属性 添加到AddRuleForm.attrs中
        this.onlyGoodsParams.forEach(item => {
          // console.log(item)
          this.AddRuleForm.attrs.push({
            attr_id:item.attr_id,
            attr_value:item.attr_vals
          })
        })
        console.log(this.AddRuleForm)
        // 发请求添加商品
        const {data:res} = await this.$http.post('goods',this.AddRuleForm)
        if(res.meta.status == 201) {
          // 添加成功后跳转商品列表页
          this.$router.push('/goods')
        }
      })
    }
  },
  computed: {
    catId() {
      if (this.cascaderOpt.length == 3) {
        return this.cascaderOpt[2]
      }
      return null
    }
  },
  created() {
    this.getGoodsCate()
  }
}
</script>

<style lang='css' scoped>
.el-steps {
  margin: 20px 0;
}
</style>
